package com.xxtx.trade.web.userCenter;

import com.xxtx.trade.common.util.model.Result;
import com.xxtx.trade.jwt.BaseContextHandler;
import com.xxtx.trade.sysUser.dto.*;
import com.xxtx.trade.sysUser.service.TradeSysUserService;
import org.bouncycastle.cert.ocsp.Req;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/api/v1/xxtx/tiktok")
public class SysTiktokController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysTiktokController.class);
    @Autowired
    private TradeSysUserService tradeSysUserService;



    /**
     *  表单采集
     * @param response
     * @param request
     * @return
     */
//    @RequestMapping(value = "/get/dianji/zj", method = RequestMethod.GET)
//    public Result getdianjizjh(HttpServletResponse response, HttpServletRequest request) {
//        String imei = request.getParameter("imei");
//        if (imei==null||imei.equals("")){
//            return Result.error("imei为空");
//        }
//        String idfa = request.getParameter("idfa");
//        if (idfa==null){
//            idfa="";
//        }
//        String oaid = request.getParameter("oaid");
//        if (oaid==null){
//            oaid="";
//        }
//        String oaid_md5 = request.getParameter("oaid_md5");
//        if (oaid_md5==null){
//            oaid_md5="";
//        }
//        String campaign_name = request.getParameter("aid_name");
//        if (campaign_name==null){
//            campaign_name="";
//        }
//        String myName = request.getParameter("myName");
//
//        tradeSysUserService.insertDouyingDatas(imei,idfa,oaid,oaid_md5,campaign_name,myName);
//        return Result.success();
//    }

    /**
     * wzyk修改：表单采集，没有修改
     */
    @RequestMapping(value = "/get/dianji/zj", method = RequestMethod.GET)
    public Result getdianjizjh(HttpServletResponse response, HttpServletRequest request) {
        String imei = request.getParameter("imei");
        tiktokInfoDto dto = new tiktokInfoDto();
        if (imei == null || imei.equals("")) {
            imei = "*";
        }
        dto.setImei(imei);

        String idfa = request.getParameter("idfa");
        if (idfa == null) {
            idfa = "";
        }
        dto.setIdfa(idfa);

        String oaid = request.getParameter("oaid");
        if (oaid == null) {
            oaid = "";
        }
        dto.setOaid(oaid);

        String oaid_md5 = request.getParameter("oaid_md5");
        if (oaid_md5 == null) {
            oaid_md5 = "";
        }
        dto.setOaid_md5(oaid_md5);

        String campaign_name = request.getParameter("campaign_name");
        if (campaign_name == null) {
            campaign_name = "";
        }
        dto.setCampaign_name(campaign_name);

        String aid = request.getParameter("aid");
        if (aid == null){
            aid = "";
        }
        dto.setAid(aid);

        String aid_name = request.getParameter("aid_name");
        if (aid_name == null){
            aid_name = "";
        }
        dto.setAid_name(aid_name);

        String advertiser_id = request.getParameter("advertiser_id");
        if (advertiser_id == null){
            advertiser_id = "";
        }
        dto.setAdvertiser_id(advertiser_id);

        String cid = request.getParameter("cid");
        if (cid == null){
            cid = "";
        }
        dto.setCid(cid);

        String cid_name = request.getParameter("cid_name");
        if (cid_name == null){
            cid_name = "";
        }
        dto.setCid_name(cid_name);

        String campaign_id = request.getParameter("campaign_id");
        if (campaign_id == null){
            campaign_id = "";
        }
        dto.setCampaign_id(campaign_id);

        String ctype = request.getParameter("ctype");
        if (ctype == null){
            ctype = "";
        }
        dto.setCtype(ctype);

        String csite = request.getParameter("csite");
        if (csite == null){
            csite = "";
        }
        dto.setCsite(csite);

        String convert_id = request.getParameter("convert_id");
        if (convert_id == null){
            convert_id = "";
        }
        dto.setConvert_id(convert_id);

        String request_id = request.getParameter("request_id");
        if (request_id == null){
            request_id = "";
        }
        dto.setRequest_id(request_id);

        String sl = request.getParameter("sl");
        if (sl == null){
            sl = "";
        }
        dto.setSl(sl);

        String androidid = request.getParameter("androidid");
        if (androidid == null){
            androidid = "";
        }
        dto.setAndroidid(androidid);

        String os = request.getParameter("os");
        if (os == null){
            os = "";
        }
        dto.setOs(os);

        String mac = request.getParameter("mac");
        if (mac == null){
            mac = "";
        }
        dto.setMac(mac);

        String mac1 = request.getParameter("mac1");
        if (mac1 == null){
            mac1 = "";
        }
        dto.setMac1(mac1);

        String ip = request.getParameter("ip");
        if (ip == null){
            ip = "";
        }
        dto.setIp(ip);

        String ua = request.getParameter("ua");
        if (ua == null){
            ua = "";
        } else {
            if (ua.length()>100){
                ua = ua.substring(0, 100);
            }
        }
        dto.setUa(ua);

        String geo = request.getParameter("geo");
        if (geo == null){
            geo = "";
        }
        dto.setGeo(geo);

        String ts = request.getParameter("ts");
        if (ts == null){
            ts = "";
        }
        dto.setTs(ts);

        String callback_param = request.getParameter("callback_param");
        if (callback_param == null){
            callback_param = "";
        }
        callback_param = "";// 这里暂时不需要了
        dto.setCallback_param(callback_param);

        String callback_url = request.getParameter("callback_url");
        if (callback_url == null){
            callback_url = "";
        } else {
            if (callback_url.length()>100){
                callback_url = callback_url.substring(0, 100);
            }
        }
        dto.setCallback_url(callback_url);

        String model = request.getParameter("model");
        if (model == null){
            model = "";
        }
        dto.setModel(model);

        String union_site = request.getParameter("union_site");
        if (union_site == null){
            union_site = "";
        }
        dto.setUnion_site(union_site);

        String caid1 = request.getParameter("caid1");
        if (caid1 == null){
            caid1 = "";
        }
        dto.setCaid1(caid1);

        String caid2 = request.getParameter("caid2");
        if (caid2 == null){
            caid2 = "";
        }
        dto.setCaid2(caid2);


        String myName = request.getParameter("myName");
        dto.setMyName(myName);

        List<String> is_empty = new ArrayList<>();
        is_empty.add("__IMEI__");
        is_empty.add("__IDFA__");
        is_empty.add("__OAID__");
        is_empty.add("__OAID_MD5__");
        is_empty.add("*");
        is_empty.add("");
        is_empty.add("00000000-0000-0000-0000-000000000000");
        is_empty.add(" ");

        // 过滤空数据，没有设备标识的数据
        if (is_empty.contains(imei) && is_empty.contains(idfa) && is_empty.contains(oaid) && is_empty.contains(oaid_md5)) {
            return Result.error("空数据");
        }
//        tradeSysUserService.insertDouyingDatas(imei, idfa, oaid, oaid_md5, campaign_name, myName);

        String key = "";
//        LOGGER.info(dto.toString());
        // 设置七天过期时间,key格式urlName
        if (!is_empty.contains(imei)) {
            key = "url=" + myName + "_imei=" + imei;
            tradeSysUserService.insertDouyingDatas(dto, key);
            return Result.success();
        }

        if(!is_empty.contains(idfa)){
            key = "url=" + myName + "_idfa=" + idfa;
            tradeSysUserService.insertDouyingDatas(dto, key);
            return Result.success();
        }

        if(!is_empty.contains(oaid)){
            key = "url=" + myName + "_oaid=" + oaid;
            tradeSysUserService.insertDouyingDatas(dto, key);
            return Result.success();
        }

        if(!is_empty.contains(oaid_md5)){
            key = "url=" + myName + "_oaid_md5=" + oaid_md5;
            tradeSysUserService.insertDouyingDatas(dto, key);
            return Result.success();
        }
//        tradeSysUserService.insertDouyingDatas(imei, idfa, oaid, oaid_md5, campaign_name, myName);
        return Result.error("空数据");
    }


    /**
     * 数据总览
     */
    @RequestMapping(value = "/get/count/data", method = RequestMethod.POST)
    public Result getCountData() throws Exception {
        return tradeSysUserService.getCountData();
    }

    /**
     * 按条件单独查询近十日的数据
     */
    @RequestMapping(value = "/get/count/data/condition", method = RequestMethod.POST)
    public Result getCountDataCondition(@RequestBody Map<String, Object> data) {
        List<Integer> li = (List<Integer>) data.get("data");
        if (li.size() == 0) {
            return tradeSysUserService.getCountDataCondition(0, "");

        } else {
            return tradeSysUserService.getCountDataCondition(li.size(), String.valueOf(li.get(li.size() - 1)));
        }
    }

    /**
     * 按条件进行数据汇总，数据数目整理，仅用于初次生成当日前十日的数据
     */
    @RequestMapping(value = "/tidy/count/data/condition", method = RequestMethod.GET)
    public Result tidyCountDataCondition() {
        return tradeSysUserService.tidyCountDataCondition();
    }


    /**
     * 查看列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result list(@RequestBody TradeSysRoleDto tradeSysRoleDto) {
        return tradeSysUserService.tiktokList(tradeSysRoleDto);
    }

    /**
     * 不分页
     */
    @RequestMapping(value = "/list/all", method = RequestMethod.POST)
    public Result listAll(@RequestBody TradeSysRoleDto tradeSysRoleDto) {
        return tradeSysUserService.selectAlltiktokUrls();
    }


    /**
     * wzyk新增：客户所属链接列表更新
     */
    @RequestMapping(value = "/permissionList/all", method = RequestMethod.POST)
    public Result permissionListAll(@RequestBody TradeSysRoleDto tradeSysRoleDto) {
        return tradeSysUserService.selectPermissionTiktokUrls(tradeSysRoleDto);
    }

    /**
     * wzyk新增，用于数据汇总页，近十日点击数据分析，选择显示单条连接或者某个客户的全部链接
     */
    @RequestMapping(value = "/nearlyClickUrls", method = RequestMethod.GET)
    public Result nearlyClickUrls() {
        return tradeSysUserService.nearlyClickUrls();
    }


    /**
     * 查看列表
     */
    @RequestMapping(value = "/list/info", method = RequestMethod.POST)
    public Result listIngo(@RequestBody TradeSysRoleDto tradeSysRoleDto) {
        return tradeSysUserService.tiktokInfoList(tradeSysRoleDto);
    }


    /**
     * wzyk新增：根据权限返回不同类型的数据
     * <p>
     * 载荷：{"perPageNum": 15, "pageNo": 1}
     */
    @RequestMapping(value = "/list/permissionInfo", method = RequestMethod.POST)
    public Result permissionListInfo(@RequestBody TradeSysRoleDto tradeSysRoleDto) {
        return tradeSysUserService.tiktokPermissionInfoList(tradeSysRoleDto);
    }


    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public Result insert(@RequestBody TradeSysRoleDto tradeSysRoleDto) {
        return tradeSysUserService.tiktokInsert(tradeSysRoleDto);
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(@RequestBody TradeSysRoleDto tradeSysRoleDto) {
        return tradeSysUserService.tiktokUpdate(tradeSysRoleDto);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result delete(@RequestBody TradeSysRoleDto tradeSysRoleDto) {
        return tradeSysUserService.tiktokDelete(tradeSysRoleDto);
    }

    /**
     * 删除url
     * **/
    @RequestMapping(value = "/deleteUrl", method = RequestMethod.POST)
    public Result deleteUrl(@RequestBody TradeSysRoleDto tradeSysRoleDto){
        return tradeSysUserService.deleteUrl(tradeSysRoleDto);
    }



    // 用于插入抖音爬取记录
    @RequestMapping(value = "/playwright/comment/log", method = RequestMethod.POST)
    public void InsertPlaywrightCommentLog(@RequestBody PlaywrightCommentLogDto playwrightCommentLogDto) {
        // 爬取记录保存
        tradeSysUserService.insertTiktokPlaywrightCommentLog(playwrightCommentLogDto);
    }

    // 账号记录
    @RequestMapping(value = "/playwright/account", method = RequestMethod.POST)
    public void InsertPlaywrightAccount(@RequestBody PlaywrightUserDto playwrightUserDto) {
        // 用户账号保存
        tradeSysUserService.addTiktokPlaywrightUser(playwrightUserDto);
    }

    @RequestMapping(value = "/playwright/comment")
    public void InsertPlaywrightComment(@RequestBody PlaywrightCommentDto playwrightCommentDto) {
        tradeSysUserService.addTiktokPlaywrightComment(playwrightCommentDto);
    }


}
